//
//  AppDelegate.m
//  DoctorProject
//
//  Created by zhibao on 2021/11/3.
//

#import "AppDelegate.h"
#import "LNavigationViewController.h"
#import <StoreKit/StoreKit.h>
#import <AliyunOSSiOS/OSSModel.h>
#import <AliyunOSSiOS/OSSClient.h>

@interface AppDelegate ()<SKPaymentTransactionObserver>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [Helper getWANIP];
    [UMConfigure initWithAppkey:@"65d3404d95b14f599d279685" channel:@"APP Store"];
    [MobClick setAutoPageEnabled:YES];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    if([UserInfoManager sharedManager].isLogin){
        [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
            
        }];
    }
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    /*
     * 初始化
     */
    
    //导航
    [self setNavConfig];
    //初始化
    [self setTabbarController];
    
    [self.window makeKeyAndVisible];
    
    [[UserInfoManager sharedManager] userInit];
    
    [[HttpHelper sharedInstance] sendGet:@"oss/token" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        DLog(@"responseObject==%@",responseObject.data);
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        NSString *endpoint = @"http://oss-cn-beijing.aliyuncs.com";
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        NSString *accessKeyId = responseObject.data[@"AccessKeyId"];
        NSString *accessKeySecret = responseObject.data[@"AccessKeySecret"];
        // 从STS服务获取的安全令牌（SecurityToken）。
        NSString *securityToken = responseObject.data[@"SecurityToken"];

        id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
        [MYGlobal share].client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider];
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
    return YES;
}

- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return NO;
}

- (void)setTabbarController {
    
    NSString *tempFirstStr = [[NSUserDefaults standardUserDefaults] valueForKey:WelcomeFlag];
    MYAPP.window.rootViewController = [UIViewController new];
    DLog(@"eeeee===%@",[UserInfoManager sharedManager].vip_expiry_date);
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2025-07-21 20:00:00"]) {
        [MYGlobal share].wechatFlag = 1;
    }
    
    if (tempFirstStr.length > 4) {
        [[UserInfoManager sharedManager] userInit];
        TabBarController *tabbarController = [[TabBarController alloc] init];
        MYAPP.tarbar = tabbarController;
        self.window.rootViewController = tabbarController;
//        if([UserInfoManager sharedManager].isVip){
//            TabBarController *tabbarController = [[TabBarController alloc] init];
//            MYAPP.tarbar = tabbarController;
//            self.window.rootViewController = tabbarController;
//        }else{
//            SelectPayController *controller = [[SelectPayController alloc] init];
//            LNavigationViewController *nav = [LNavigationViewController rootVC:controller];
//            nav.gk_openScrollLeftPush = YES;
//            nav.gk_openSystemNavHandle = YES;
//            MYAPP.window.rootViewController = nav;
//        }
    }else{
        MYAPP.window.rootViewController = [WelcomeController new];
    }
}

- (void)setNavConfig {
    //    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // 配置导航栏属性
    [GKConfigure setupCustomConfigure:^(GKNavigationBarConfigure *configure) {
        //       configure.gk_translationX = 15;
        //       configure.gk_translationY = 20;
        configure.backgroundColor = MyColor(@"#000000");
        configure.titleFont = MY_SCALE_RegularFONT(18);
        configure.titleColor = MyColor(@"#000000");
        //       configure.gk_scaleX = 0.90;
        configure.backImage = [UIImage imageNamed:@"arrow_back_white"];
        //       configure.gk_scaleY = 0.92;
        configure.gk_navItemLeftSpace = 12.0f;
        configure.gk_navItemRightSpace = 12.0f;
    }];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = YES;
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0); {
    
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
   
    return YES;
}


#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    DLog(@"程序将要进入前台");
}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    if(![UserInfoManager sharedManager].isLogin){
        return;
    }
    if(transactions.count > 0){
        SKPaymentTransaction *tran = transactions.lastObject;
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                [self verifyPurchaseWithPaymentTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                
                break;
            default:
                break;
        }
    }
}
- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    //交易验证
    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    if(!receipt){
        return;
    }
    NSString *idkey = [DWKeychainTool getItemForKey:@"id"];
    NSString *time = [Helper getTime:TimeTypeZhou];
    if([idkey isEqualToString:@"com.yuliang.yue"]){
        time = [Helper getTime:TimeTypeYue];
    }else if([idkey isEqualToString:@"com.yuliang.ji"]){
        time = [Helper getTime:TimeTypeJi];
    }else if([idkey isEqualToString:@"com.yuliang.year"]){
        time = [Helper getTime:TimeTypeNian];
    }
    [MobClick event:@"dingyue" attributes:@{@"type":@"xuding", @"id":transaction.payment.productIdentifier}];
    [DWKeychainTool saveItem:time key:@"vip"];
    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
        
    }];
}

@end
